var net = require('net');
var ClientItem = require('./ClientItem.js');
var clientList = require('./ClientList.js');

// var
var server = net.createServer();

// connection
server.on('connection', function(socket) {
	var clientDes = socket.remoteAddress + ':' + socket.remotePort;
	console.log('new connection:' + clientDes);

	// require client send info 
	socket.write('require send info');
	socket.on('data', function(chunk) {
		onReceiveClientData(socket, chunk)
	});

	// end
	socket.on('end', function() {
		console.log('end ' + clientDes);
		var clientOne = clientList.getClientBySocket(socket);
		if (clientOne) {
			clientList.remove(clientOne);
		}
	});

	// error
	socket.on('error', function(e) {
		console.log('error ' + clientDes + '\n' + e);
	});
});

// const
var tick = 'tick';
var prefix = 'appDeviceInfo&'
var REG_WAIT_TIME = 5000; // register must soon
function onReceiveClientData(socket, chunk) {
	var data = chunk.toString();
	console.log(data);

	var notRegYet = true;
	if (!clientList.getClientBySocket(socket)) {
		var regIn5 = setTimeout(function() {
			console.log('not register in 5');
			socket.end();
		}, REG_WAIT_TIME);
	}

	if (tick === data) { // tick, simple return tick
		console.log('get tick');
		var aClient = clientList.getClientBySocket(socket);
		if (aClient) {
			clientList.sendMsg(aClient.clientInfo, tick);
			aClient.refresh();
		} else {
			console.log('unknown socket tick');
		}
	} else {
		// check register
		if (data.indexOf(prefix) === 0) {
			console.log('register');
			clearTimeout(regIn5); // remove timer
			var newClient = new ClientItem(data, socket);
			clientList.add(newClient);
		} else {
			console.log('undefined msg from client:' + data);
		}
	}
}

function startListen() {
	console.log('sockert start at 3001...');
	server.listen(3001);
}

var wakeUp = 'wakeUp';

function wakeupOneMobile(clientInfo) {
	console.log('wakeup ' + clientInfo);
	clientList.sendMsg(clientInfo, wakeUp);
}

function wakeupManyMobile(clientInfoArray) {
	if (!clientInfoArray || !Array.isArray(clientInfoArray)) {
		console.log('clientInfoArray illegal');
		return;
	}
	clientInfoArray.forEach(wakeupOneMobile);
}

function wakeup(infoOrInfoArr) {
	if (Array.isArray(infoOrInfoArr)) {
		wakeupManyMobile(infoOrInfoArr);
	} else {
		wakeupOneMobile(infoOrInfoArr);
	}
}

module.exports = {
	startListen: startListen,
	wakeup: wakeup,
	getAllOnline: clientList.getAllOnline
}